package com.xw.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xw.common.Constants;
import com.xw.dao.CommentDao;
import com.xw.entity.Comment;
import com.xw.exp.ServiceException;
import com.xw.req.PageRequest;
import com.xw.service.CommentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @Description: 针对表【comment】的数据库操作Service实现
 * @Author: 72478
 * @Date: 2024/12/18 16:53
 * @Version: 1.0
 */
@Service("commentService")
public class CommentServiceImpl implements CommentService {
    @Resource
    private CommentDao commentDao;

    /**
    * 分页查询
    *
    * @return 查询结果
    */
    @Override
    public PageInfo<Comment> queryByPage(PageRequest<Comment> pageRequest) {
        if (pageRequest.getQ() == null || pageRequest.getQ().getPostCodeId() == null) {
            throw new ServiceException(Constants.ERROR.getCode(), "参数错误！");
        }
        //开始分页
        pageRequest.getQ().setLinkId(0);
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
        List<Comment> list = this.commentDao.queryAll(pageRequest.getQ());
        PageInfo<Comment> pageInfo = new PageInfo<>(list);
        // 查询该帖子下的所有评论数据
        Comment query = new Comment();
        query.setPostCodeId(pageRequest.getQ().getPostCodeId());
        List<Comment> commentList = this.commentDao.queryAll(query);

        for (Comment comment : pageInfo.getList()) {
            List<Comment> childrenList = new ArrayList<>();
            recursion(comment,commentList,false,childrenList);
            comment.setChildren(childrenList);
        }
        return pageInfo;
    }

    // recursion
    private void recursion(Comment comment,List<Comment> commentList,boolean isSet,List<Comment> childrenList) {
        List<Comment> collect = commentList.stream().filter(u -> u.getLinkId().compareTo(comment.getId()) == 0).collect(Collectors.toList());
        for (Comment cm : collect) {
            if (isSet) {
                cm.setUserId(comment.getCommentUserId());
                cm.setUserName(comment.getCommentUserName());
                cm.setUserPic(comment.getCommentUserPic());
            }
            childrenList.add(cm);
            recursion(cm,commentList,true,childrenList);
        }
    }
}
